/**
 * Created by ��־�� on 2017/2/17.
 */
import React from 'react';
import crypto from "crypto";
import {Comment} from "../comment";
import {IfDispatcher} from "../store/dispatcher";

export var Fronpage = React.createClass({

    contextTypes: {
        router: React.PropTypes.object.isRequired,
    },
    getInitialState(){
       var loginInfo = this.props.loginInfo;
             if(loginInfo.name){
                 if(!loginInfo.iftamr){
                     this.context.router.push("/project");
                 }else{
                     IfDispatcher.dispatch({
                         actionType:Comment.LOGOUT
                     });
                 }
             }
       // if($.cookie('authToken')){
       //     if($.cookie('authToken') !=""){
       //         var that = this;
       //         $.ajax({
       //             url: Comment.DATA_URL+"KDB/SendUUIDToTamr",
       //             data: $.param({
       //                 uuid:$.cookie('authToken'),
       //             }),
       //             type: 'POST',
       //             contentType: 'application/x-www-form-urlencoded',
       //             success: function (data) {
       //                 // alert("success");
       //                 var msg = data;
       //                 //$("#ajaxloading").hide();
       //                 IfDispatcher.dispatch({
       //                     actionType: Comment.TAMRLOGINSUCCESS,
       //                     name:msg.data.userName,
       //                     pass:msg.data.Password,
       //                     userid:msg.data.userId,
       //                     ifadmin:msg.data.Isadmin,
       //                     uuid:msg.data.uuid,
       //                 });
       //                 //setTimeout(that.proonclick(),100);
       //                 that.context.router.push("/project");
       //             },
       //             error:function(){
       //                 // $("#ajaxloading").hide();
       //             },
       //             statusCode:{
       //                 415:function(){
       //                     alert("Tamr User authentication failed.");
       //                 },
       //             }
       //         });
       //     }
       // }else{
       //     if(loginInfo.name){
       //         //var btnClor = {};
       //         //btnClor .btn = "#FFFFFF";
       //         //btnClor .btn1 = "#E0E0E0";
       //         //btnClor .btn2 = "#E0E0E0";
       //         //localStorage.setItem("btnClor",JSON.stringify(btnClor));
       //         if(loginInfo.iftamr){
       //             var that = this;
       //             $.ajax({
       //                 url: Comment.DATA_URL+"KDB/SendUUIDToTamr",
       //                 data: $.param({
       //                     uuid:loginInfo.uuid,
       //                 }),
       //                 type: 'POST',
       //                 contentType: 'application/x-www-form-urlencoded',
       //                 success: function (data) {
       //                     // alert("success");
       //                     //var msg = data;
       //                     //$("#ajaxloading").hide();
       //                     //IfDispatcher.dispatch({
       //                     //    actionType: Comment.TAMRLOGINSUCCESS,
       //                     //    name:msg.data.userName,
       //                     //    pass:msg.data.Password,
       //                     //    userid:msg.data.userId,
       //                     //    ifadmin:msg.data.Isadmin,
       //                     //    uuid:msg.data.uuid,
       //                     //});
       //                     //setTimeout(that.proonclick(),500);
       //                     that.context.router.push("/project");
       //                 },
       //                 error:function(){
       //                     // $("#ajaxloading").hide();
       //                 },
       //                 statusCode:{
       //                     415:function(){
       //                         alert("Tamr User authentication failed.");
       //                     },
       //                 }
       //             });
       //         }else{
       //             this.context.router.push("/project");
       //         }
       //     }
       // }
        return{
            username:"",
            password:"",
            iferror:false,
            ifusererror:false,
            ifactive:true,
            capcha:"",
            newcapcha:Math.random(),
            capchastyle:false,
            ifcapcha:0,
            iflocked:false,
            lockedtime:null,
            timeinterval:false,
        }
    },
    componentDidMount (){

    },
    handleChange(name,event){
        var newstate ={};
        newstate[name] = event.target.value;
        newstate.iferror = false;
        newstate.ifusererror=false;
        newstate.ifactive= true;
        newstate.iflocked= false;
        newstate.lockedtime= null;
        newstate.ifcapcha= 0;
        newstate.timeinterval=false;
        this.setState(newstate);
    },
    proonclick(){
        //var btn = document.getElementById("Projectzzl");
        //btn.style.background = "#FFFFFF";
        //var btn1 = document.getElementById("Dictionaryzzl");
        //btn1.style.background = "#E0E0E0";
        //var btn2 = document.getElementById("DataFeaturezzl");
        //btn2.style.background = "#E0E0E0";
        //var btnClor = {};
        //btnClor .btn = btn.style.background;
        //btnClor .btn1 = btn1.style.background;
        //btnClor .btn2 = btn2.style.background;
        //localStorage.setItem("btnClor",JSON.stringify(btnClor));
        this.context.router.push("/project");
    },
    adminclick(){
        this.context.router.push("/account");
    },
    staffclick(){
        this.context.router.push("/staff");
    },
    inputClick(name,event){
      //  var keys = crypto.pbkdf2Sync(this.state.password, this.state.password+Math.random()*10000, 100, 16, 'sha512');
      //  var keys = crypto.pbkdf2Sync(this.state.password, 'eseasky', 100, 16, 'sha512');
      //  alert(keys.toString('hex'));
      //  alert(keys.toString('hex').length);
        var newstate ={};
        newstate.iferror = false;
        newstate.ifusererror=false;
        newstate.ifactive= true;
        newstate.iflocked= false;
        newstate.lockedtime= null;
        newstate.timeinterval=false;
        newstate.ifcapcha= 0;
        this.setState(newstate);
        if(!this.state.username || !this.state.password){
            this.setState({iferror:true});
        }else{
            if(!this.state.capcha){
                this.setState({
                    ifcapcha:1,
                    newcapcha:Math.random(),
                    capcha:"",
                });
            }else{
                var that = this;
                $("#ajaxloading").show();
                $.ajax({
                    url: Comment.DATA_URL+"KDB/GetSalt",
                    data: $.param({
                        username:that.state.username
                    }),
                    type: 'GET',
                    contentType: 'application/x-www-form-urlencoded',
                    success: function (data) {
                        var msg = data;
                        var salt = msg.data;
                        var keys = crypto.pbkdf2Sync(that.state.password, salt, 10000, 16, 'sha512');
                        //alert(1);
                        $.ajax({
                            url: Comment.DATA_URL+"KDB/CheckLogin",
                            data: $.param({
                                username:that.state.username,
                                // password:hash.digest("hex"),
                                password:keys.toString('hex'),
                                captcha:that.state.capcha,
                            }),
                            type: 'POST',
                            contentType: 'application/x-www-form-urlencoded',
                            success: function (data) {
                                 //alert("success");
                                var msg = data;
                                $("#ajaxloading").hide();
                                if(msg.status === "201"){
                                    if(msg.data.Isadmin){
                                        IfDispatcher.dispatch({
                                            actionType: Comment.LOGINSUCCESS,
                                            name:msg.data.userName,
                                            // pass:msg.data.Password,
                                            pass:null,
                                            userid:msg.data.userId,
                                            iffrist:true,
                                            ifadmin:msg.data.Isadmin,
                                        });
                                        setTimeout(that.staffclick(),500);
                                    }else{
                                        IfDispatcher.dispatch({
                                            actionType: Comment.LOGINSUCCESS,
                                            name:msg.data.userName,
                                            // pass:msg.data.Password,
                                            pass:null,
                                            userid:msg.data.userId,
                                            iffrist:true,
                                            ifadmin:msg.data.Isadmin,
                                        });
                                        setTimeout(that.staffclick(),500);
                                    }
                                }else{
                                    IfDispatcher.dispatch({
                                        actionType: Comment.LOGINSUCCESS,
                                        name:msg.data.userName,
                                        // pass:msg.data.Password,
                                        pass:null,
                                        userid:msg.data.userId,
                                        iffrist:false,
                                        ifadmin:msg.data.Isadmin,
                                    });
                                    setTimeout(that.proonclick(),500);
                                }
                            },
                            error:function(){
                                $("#ajaxloading").hide();
                            },
                            statusCode:{
                                413:function(){
                                    $.ajax({
                                        url: Comment.DATA_URL + "KDB/GetConfInfo",
                                        type: 'GET',
                                        //headers: {
                                        //    Accept: "*/*,application/x-javascript"
                                        //},
                                        contentType: 'application/x-www-form-urlencoded',
                                        success: function (data) {
                                            that.setState({
                                                iflocked:true,
                                                lockedtime:data.data.login_lock_time,
                                                newcapcha:Math.random(),
                                                capcha:"",
                                            })
                                        },
                                        error: function () {
                                            $("#ajaxloading").hide();
                                            that.setState({
                                                iflocked:true,
                                                lockedtime:null,
                                                newcapcha:Math.random(),
                                                capcha:"",
                                            })
                                        },
                                    });
                                },
                                414:function(){
                                    that.setState({
                                        iferror:true,
                                        newcapcha:Math.random(),
                                        capcha:"",
                                    })
                                },
                                415:function(){
                                    that.setState({
                                        ifusererror:true,
                                        newcapcha:Math.random(),
                                        capcha:"",
                                    })
                                },
                                416:function(){
                                    that.setState({
                                        ifactive:false,
                                        newcapcha:Math.random(),
                                        capcha:"",
                                    })
                                },
                                417:function(){
                                    that.setState({
                                        ifcapcha:2,
                                        newcapcha:Math.random(),
                                        capcha:"",
                                    })
                                },
                                429:function(){
                                    that.setState({timeinterval:true});
                                }
                            }
                        });
                    },
                    error:function(){
                        $("#ajaxloading").hide();
                    },
                    statusCode:{
                        424:function(){
                            that.setState({
                                ifusererror:true,
                                newcapcha:Math.random(),
                                capcha:"",
                            })
                        },
                    }
                });
                //var b = Base64.encode(this.state.password);
                //alert(b);
                //var c = Base64.decode(b);
                //alert(c);
                //var hash = crypto.createHash("md5");
                //hash.update(this.state.password);
            }
        }
    },
    keyLogin(event){
        if(event.key == "Enter"){
            this.inputClick(event);
        }
    },
    capchaClick(){
        this.setState({
            newcapcha:Math.random()
        })
    },
    onfocusclick(){
        this.setState({
            capchastyle:true,
        })
    },
    inputTamrClick(){
        if($.cookie('authToken')){
            if($.cookie('authToken') !=""){
                var that = this;
                $.ajax({
                    url: Comment.DATA_URL+"KDB/SendUUIDToTamr",
                    data: $.param({
                        uuid:$.cookie('authToken'),
                    }),
                    type: 'POST',
                    contentType: 'application/x-www-form-urlencoded',
                    success: function (data) {
                        var msg = data;
                        IfDispatcher.dispatch({
                            actionType: Comment.TAMRLOGINSUCCESS,
                            name:msg.data.userName,
                            pass:msg.data.Password,
                            userid:msg.data.userId,
                            ifadmin:msg.data.Isadmin,
                            uuid:msg.data.uuid,
                        });
                        setTimeout(that.proonclick(),100);
                        //that.context.router.push("/project");
                    },
                    error:function(){
                        // $("#ajaxloading").hide();
                    },
                    statusCode:{
                        415:function(){
                            alert("Tamr User authentication failed.");
                        },
                    }
                });
            }else{
                this.context.router.push("/tamrlogin");
            }
        }else{
            this.context.router.push("/tamrlogin");
        }
    },
    render(){
        var disStyle = this.state.iferror?{}:{display:"none"};
        var userStyle = this.state.ifusererror?{}:{display:"none"};
        var ifactiveStyle = this.state.ifactive?{display:"none"}:{};
        var capchastyle = this.state.capchastyle?{}:{display:"none"};
        var iflockedStyle = this.state.iflocked?{}:{display:"none"};
        var iftimeinterval = this.state.timeinterval?{}:{display:"none"};
        var capchaerror = {display:"none"};
        var capchaempty = {display:"none"};
        if(this.state.ifcapcha == 1){
            capchaempty = {};
        }else if(this.state.ifcapcha == 2){
            capchaerror = {};
        }
        return(
            <div className="divrow" style={{marginTop:"0px",height:(this.props.propsheight+"px")}} >

                <div className="row" style={{marginLeft:"0px",clear:"both",marginRight:"0px"}}>
                    <div className="col-sm-4 col-sm-offset-4" style={{paddingTop:"100px"}}>
                        <div className="panel panel-default" >
                            <div className="panel-body formstyleone" style={{backgroundColor:"#282E3E"}}>
                                <form>
                                    <div className="row">
                                        <div className="col-sm-12" style={{textAlign:"center",color:"#fff",fontSize:"20px"}}>
                                            <span>User Login</span>
                                        </div>
                                    </div>
                                    <div className="row" style={{marginTop:"10px"}}>
                                        <label className="col-sm-3 control-label" ><h5 style={{color:"#fff"}}>Username:</h5></label>
                                        <div className="col-sm-8">
                                            <input type="text"
                                                   className="form-control"
                                                   id="fpgusername"
                                                   placeholder="Username"
                                                   style={{height:"40px"}}
                                                   value={this.state.username}
                                                   onChange={this.handleChange.bind(this,"username")}
                                                   onFocus={this.onfocusclick}
                                                   onMouseOver={copyPaste("fpgusername")}
                                                />
                                        </div>
                                    </div>
                                    <div className="row" style={{marginTop:"10px"}}>
                                        <label className="col-sm-3 control-label" ><h5 style={{color:"#fff"}}>Password:</h5></label>
                                        <div className="col-sm-8">
                                            <input type="password"
                                                   className="form-control"
                                                   placeholder="Password"
                                                   id="fpgpasszzl"
                                                   style={{height:"40px"}}
                                                   onKeyPress={this.keyLogin}
                                                   value={this.state.password}
                                                   onChange={this.handleChange.bind(this,"password")}
                                                   onMouseOver={copyPaste("fpgpasszzl")}
                                                />
                                        </div>
                                    </div>
                                    <div style={capchastyle}>
                                        <div className="row" style={{marginTop:"10px"}}>
                                            <label className="col-sm-3 control-label" ><h5 style={{color:"#fff"}}>Capcha:</h5></label>
                                            <div className="col-sm-8 ">
                                                <div className="row">
                                                    <div className="col-sm-6">
                                                        <input type="text"
                                                               style={{height:"40px"}}
                                                               className="form-control"
                                                               placeholder="Capcha"
                                                               value={this.state.capcha}
                                                               onChange={this.handleChange.bind(this,"capcha")}
                                                               onKeyPress={this.keyLogin}
                                                            />
                                                    </div>
                                                    <div className="col-sm-6 " >
                                                        <div className="row" style={{marginLeft:"0px",marginRight:"0px"}}>
                                                            <img style={{width:"100%",height:"40px"}}onClick={this.capchaClick} src={Comment.DATA_URL+"KDB/SendCaptcha"+"?"+this.state.newcapcha} />
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row" style={{marginTop:"10px"}}>
                                        <div className="col-sm-8 col-sm-offset-3">
                                            <input type="button"
                                                   onClick={this.inputClick}
                                                   value="Log In"
                                                   className="form-control btn btn-primary"
                                                   style={{height:"40px",color:"#F0F0F0"}}
                                                />
                                        </div>
                                    </div>
                                    <div className="row" style={{marginTop:"10px"}}>
                                        <div className="col-sm-offset-1 col-sm-10" style={disStyle}>
                                            <p  style={{color:"#750000",textAlign:"center"}}>The sign you entered was not correct,please try again.</p>
                                        </div>
                                        <div className="col-sm-offset-1 col-sm-10" style={iftimeinterval}>
                                            <p  style={{color:"#750000",textAlign:"center"}}>The password exceeds the maximum valid period.</p>
                                        </div>
                                        <div className="col-sm-offset-1 col-sm-10" style={userStyle}>
                                            <p  style={{color:"#750000",textAlign:"center"}}>The sign in information you entered was not correct. Please try again.</p>
                                        </div>
                                        <div className="col-sm-offset-1 col-sm-10" style={ifactiveStyle}>
                                            <p  style={{color:"#750000",textAlign:"center"}}>Not active</p>
                                        </div>
                                        <div className="col-sm-offset-1 col-sm-10" style={iflockedStyle}>
                                            <p  style={{color:"#750000",textAlign:"center"}}>Has been locked, Please try again after {this.state.lockedtime} minutes.</p>
                                        </div>
                                        <div className="col-sm-offset-1 col-sm-10" style={capchaempty}>
                                            <p  style={{color:"#750000",textAlign:"center"}}>Capcha cannot be empty.</p>
                                        </div>
                                        <div className="col-sm-offset-1 col-sm-10" style={capchaerror}>
                                            <p  style={{color:"#750000",textAlign:"center"}}>Capcha error.</p>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                </div>

            </div>
        )
    }
});